﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Modularity;
using Volo.Abp.BackgroundJobs.Hangfire;
using Volo.Abp;
using Hangfire;
using Hangfire.MySql;
using FHJFPro.AppSettings;
using Hangfire.Dashboard.BasicAuthorization;

namespace FHJFPro.BackgroundJob
{
    [DependsOn(typeof(AbpBackgroundJobsHangfireModule))]
    public class FHJFProBackgroundJobModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddHangfire(option =>
            {
                option.UseStorage(new MySqlStorage(
                    AppSetting.ConnectionStrings,
                    new MySqlStorageOptions(){
                        PrepareSchemaIfNecessary=true,//如果设置为true，则创建数据库表默认是true。
                        DashboardJobListLimit=5000,//- 仪表板作业列表限制。。
                        TransactionTimeout =TimeSpan.FromMinutes(1), //- 交易超时默认为1分钟。
                        TablesPrefix ="hangfire_"
                    })
                    );
            });
        }
        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();


            //注册hangfire服务
            app.UseHangfireServer();

            //显示仪表盘并开启账户认证
            app.UseHangfireDashboard(options: new DashboardOptions
            {
                Authorization = new[]
                 {
                    new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
                    {
                        RequireSsl = false,
                        SslRedirect = false,
                        LoginCaseSensitive = true,
                        Users = new []
                        {
                            new BasicAuthAuthorizationUser
                            {
                                Login = AppSetting.Hangfire.Login,
                                PasswordClear =  AppSetting.Hangfire.Password
                            }
                        }
                    })
                },
                DashboardTitle = "任务调度中心"
            });

            //激活执行job
            app.UseExcuteSchedulingTask();
        }
    }
}
